
// 冒泡排序
function bubleSort(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        let temp = arr[j + 1]
        arr[j + 1] = arr[j]
        arr[j] = temp
      }
    }
  }
}

// 插入排序
function insertSort(arr) {
  for (let i = 1; i < arr.length; i++) {
    let temp = arr[i]
    for (let j = i - 1; j >=0; j--) {
      if (arr[j] > temp) {
        arr[j + 1] = arr[j]
        if (j === 0) arr[j] = temp
      } else {
        arr[j + 1] = temp
        break
      }
    }
  }
}

// 选择排序
function selectSort() {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[i]) {
        let temp = arr[j]
        arr[j] = arr[i]
        arr[i] = temp
      }
    }
  }
}

// 快速排序
function quickSort(arr, left, right) {
  let i = left, j = right
  let temp = arr[i]
  while (i < j) {
    while (i < j && arr[j] >= temp) j--
    if (i < j) arr[i++] = arr[j] 
    while (i < j && arr[i] <= temp) i++
    if (i < j) arr[j--] = arr[i] 
  }
  arr[i] = temp
  if (left < i - 1)  quickSort(arr, left, i - 1)
  if (right > i + 1)  quickSort(arr, i + 1, right)
}

let arr = [5,4,7,8,3,1,2]
quickSort(arr, 0, arr.length - 1)
console.log(arr);